<?php

namespace api\modules\v1\models;

use common\helpers\RegularHelper;
use common\helpers\UploadHelper;
use phpqrcode\QRcode;
use Yii;

class ModuleImage
{
    /**
     * 生成二维码
     * @param $src
     * @param string $save_path
     * @param string $level
     * @param int $size
     * @return string|null
     */
    public static function createQrCode($src, $save_path = '', $level = 'L', $size = 4)
    {
        $base_path = dirname(Yii::$app->BasePath);
        if (empty($save_path))
            $save_path = $base_path . '/resources/cache/';

        $save_path .= md5(uniqid(mt_rand(), true)) . '.jpg';

        // 生成的文件名
        $fileName = $base_path . '/web'. $save_path;
        QRcode::png($src, $fileName, $level, $size);
        if (is_file($fileName)) {
            return RegularHelper::service() . $save_path;
        } else return null;
    }

    /**
     * 生成海报
     * @param $style
     * @param $qr_code
     * @param $params
     * @return array|string
     * @throws \League\Flysystem\FileExistsException
     * @throws \League\Flysystem\FileNotFoundException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\web\NotFoundHttpException
     */
    public static function createPoster($style, $qr_code, $params)
    {
//        header('Content-Type: image/png');//输出协议头
        $base_path = dirname(Yii::$app->BasePath);

        $style_array = [
            1 => [
                'bg' => '/resources/img/poster/1.jpg',
                'qrcode_w' => 120,
                'qrcode_h' => 120,
                'qrcode_x' => 345,
                'qrcode_y' => 662,
                'name_x' => 120,
                'name_y' => 700
            ]
        ];
        $cache_local = $base_path . '/web/resources/cache/';
        $save_url = '/resources/img/user_poster/'.$params['id'].'-'.$style.'.jpg';
        $save_path = '/web'.$save_url;

        $head_portrait = $params['head_portrait'];
        if (!$head_portrait) {
            $head_portrait = $base_path . '/web/resources/img/default_head.jpg';
        }else{
            $head_portrait = self::downloadfile($head_portrait, $cache_local);
        }

        //生成二维码
        $qrcode = self::createQrCode($qr_code, '/resources/cache/');
        if ($qrcode) {
            $style_object = $style_array[$style];
            if (!$style_object) return '海报样式有误';

            $bg_path = $base_path . '/web' . $style_object['bg'];

            list($_w, $_h) = getimagesize($bg_path);//获取你原图的宽高
            $bg_scr = imagecreatefromstring(file_get_contents($bg_path));
            $qr_scr = imagecreatefromstring(file_get_contents($qrcode));
            $head_scr = self::yuanjiao($head_portrait);
            list($_w1, $_h1) = getimagesize($qrcode);
            list($_w2, $_h2) = getimagesize($head_portrait);

//            imagecopymerge($bg_scr, $qr_scr, 317, 668, 0, 0, 220, 220, 100);
            imagecopyresampled($bg_scr, $qr_scr, $style_object['qrcode_x'], $style_object['qrcode_y'], 0, 0, $style_object['qrcode_w'], $style_object['qrcode_h'], $_w1, $_h1);
            imagecopyresampled($bg_scr, $head_scr, 40, 665, 0, 0, 70, 70, $_w2, $_h2);

            $black = imagecolorallocate($bg_scr, 0, 0, 0);
            $font = $base_path . '/web/resources/simhei.ttf';
            imagettftext($bg_scr, 20, 0, $style_object['name_x'], $style_object['name_y'], $black, $font, $params['nickname']);
            imagettftext($bg_scr, 14, 0, $style_object['name_x'], $style_object['name_y']+30, $black, $font, '邀请您一起买买买~');

            imagejpeg($bg_scr, $base_path . $save_path);
            imagedestroy($bg_scr);

//            return RegularHelper::service().$save_url;

            $upload = new UploadHelper([], 'images');
            $upload->save($upload->verifyUrl(RegularHelper::service().$save_url));
            $baseInfo = $upload->getBaseInfo();
            if($baseInfo){
                return $baseInfo;
            }

//            $imgbase64  = self::imgToBase64($base_path.$save_path);
//            $upload = new UploadHelper([], 'images');
//            $upload->verifyUrl(RegularHelper::service().$save_url);
//            return $upload->save();
//            $upload->verifyBase64($imgbase64,'jpg');
//            return $upload->save(base64_decode($imgbase64));
//            return $upload;
        } else {
            return '生成二维码错误';
        }
    }

    /**
     * 圆角
     * @param $imgpath
     * @return false|resource
     */
    protected static function yuanjiao($imgpath)
    {
        $ext = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'jpeg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
        $wh = getimagesize($imgpath);
        $w = $wh[0];
        $h = $wh[1];
        $w = min($w, $h);
        $h = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }

    /**
     * 转base64
     * @param $img_file
     * @return string
     */
    protected static function imgToBase64($img_file) {

        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限

            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }

                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

            }
            fclose($fp);
        }

        return $img_base64; //返回图片的base64
    }



    /**
     * 下载文件
     * @param $file_url
     * @param $save_to
     */
    private static function downloadfile($file_url, $save_to)
    {
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',
        ];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $file_url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
//        echo $code;
        if ($code == 200) {//把URL格式的图片转成base64_encode格式的！
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
        } else
            return false;

        $img_content = $imgBase64Code;//图片内容
        //echo $img_content;exit;
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
            $type = $result[2];//得到图片类型png?jpg?gif?
            $new_file = $save_to . time() . rand(1, 10000) . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
                return $new_file;
            } else
                return false;
        } else
            return false;
    }
}